package emulator.hardware.memory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import emulator.hardware.bus.Bus;
import emulator.hardware.debug.BusWatchException;

public class MemoryBlock implements Bus, MemoryBlockInterface {

	byte[] memory;
	
	public MemoryBlock(int size)
	{
		memory = new byte [size];
		Arrays.fill(memory, (byte)0);
	}
	
	@Override
	public int read(int address) throws UnmappedMemoryException, BusWatchException {
		return ((int) memory[address]) & 0xFF;
	}

	@Override
	public void write(int address, int data) throws UnmappedMemoryException, BusWatchException {
		memory[address] = (byte) (data & 0xFF);
	}
	
	/* (non-Javadoc)
	 * @see emulator.hardware.memory.MemoryBlockInterface#loadFromStream(java.io.InputStream, int, int)
	 */
	@Override
	public void loadFromStream(InputStream file, int address, int size) throws IOException
	{
		for (int i = 0; i < size; i++)
		{
			int ch = file.read();
			if (ch < 0)
				return;
			memory[address+i] = (byte)ch;
		}
	}

	/* (non-Javadoc)
	 * @see emulator.hardware.memory.MemoryBlockInterface#getData()
	 */
	@Override
	public byte[] getData() {
		return memory;
	}

	/* (non-Javadoc)
	 * @see emulator.hardware.memory.MemoryBlockInterface#saveToStream(java.io.OutputStream, int, int)
	 */
	@Override
	public void saveToStream(OutputStream file, int address, int size) throws IOException {
		file.write(memory, address, size);
	}

}
